import os

from pynput import mouse, keyboard
import threading
import time

from src.config.configLoader import ConfigLoader
from src.modules.bar.barResources import BarResources
from src.modules.bar.barStatus import BarStatus
from src.modules.bar.barValue import BarValue
from PIL import ImageGrab

from src.modules.skill import Skill


def get_pixel_color(x, y):
    """
    获取屏幕上指定坐标 (x, y) 的像素 RGB 颜色值
    :param x: 屏幕坐标 X
    :param y: 屏幕坐标 Y
    :return: 元组 (R, G, B) 或 None（如果出错）
    """
    try:
        # 截取单个像素点
        screenshot = ImageGrab.grab(bbox=(x, y, x + 1, y + 1))
        # 获取该像素的颜色
        color = screenshot.getpixel((0, 0))
        return color  # 返回 (R, G, B)
    except Exception as e:
        print(f"获取像素颜色失败: {e}")
        return None


# 标记鼠标侧键1是否被按下
side_button_pressed = False

# 创建一个键盘控制器
keyboard_controller = keyboard.Controller()

mouse_controller = mouse.Controller()

# 创建一个事件对象
key_event = threading.Event()


def mouse_listener():
    global side_button_pressed
    with mouse.Listener(on_click=on_click) as listener:
        listener.join()


# 侧键启动信号监听
def on_click(x, y, button, pressed):
    global side_button_pressed
    if button == mouse.Button.x1:
        side_button_pressed = pressed
        if side_button_pressed:
            key_event.set()  # 设置事件
        else:
            key_event.clear()  # 清除事件


# 主循环进行键盘技能控制
def key_press_loop():
    global side_button_pressed

    # 获取当前文件所在目录
    current_dir = os.path.dirname(os.path.abspath(__file__))

    # === 启动时加载配置 ===
    config_loader = ConfigLoader(config_path="config.json", project_root=current_dir)

    # 选择分辨率模式
    resolution = "4k"  # 或 "2k"

    # === 初始化各个模块 ===

    bar = BarValue(config_loader.get_section("barValue", resolution))
    bar_status = BarStatus(config_loader.get_section("barStatus", resolution))
    bar_resources = BarResources(config_loader.get_section("barResources", resolution))
    skill3 = Skill(config_loader.get_section("skill3", resolution))
    while True:
        key_event.wait()  # 等待事件被设置

        while side_button_pressed:

            # 判断是爆发期还是空窗期
            if bar_status.is_burst():
                print('爆发期')

                wait_time = 0
                if bar.get_value() != 100:
                    wait_time += 0.1
                if bar_resources.have_resource_of_num(3):
                    wait_time += 0.05
                keyboard_controller.tap('1')
                print('居合')
                time.sleep(wait_time)

                if all(c > 200 for c in get_pixel_color(1941, 1911)):
                    keyboard_controller.tap('5')
                    print('一闪')
                    time.sleep(0.1)
                else:
                    mouse_controller.click(mouse.Button.left, 1)
                    time.sleep(0.05)
            else:
                print('空窗期')
                if all(c > 200 for c in get_pixel_color(1941, 1911)):
                    keyboard_controller.tap('5')
                    print("一闪")
                    time.sleep(0.2)

                wait_time = 0
                if bar.get_value() != 100:
                    wait_time += 0.4
                if bar_resources.have_resource_of_num(3):
                    wait_time += 0.1
                keyboard_controller.tap('1')
                print('居合')
                time.sleep(wait_time)

                if all(c > 200 for c in get_pixel_color(1941, 1911)):
                    keyboard_controller.tap('5')
                    print("一闪")
                    time.sleep(0.2)

                if skill3.get_value() is not None and skill3.get_value() > 0 and wait_time < 0.29:
                    keyboard_controller.tap('2')
                    print("超高出力")
                    time.sleep(0.1)
                else:
                    mouse_controller.click(mouse.Button.left, 1)
                    time.sleep(0.05)


        key_event.clear()  # 清除事件


# 启动鼠标监听线程
mouse_thread = threading.Thread(target=mouse_listener, daemon=True)
mouse_thread.start()

# 启动按键循环线程
key_press_thread = threading.Thread(target=key_press_loop, daemon=True)
key_press_thread.start()

# 保持主程序运行
mouse_thread.join()
key_press_thread.join()
